package cn.edu.zafu.bigdata.x.yaojy;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class StudentManagementSystem {
    private static final String FILE_NAME = "students.dat";
    private List<Student> students;
    private Map<String,Integer> idIndexMap;

    public StudentManagementSystem(){
        students = new ArrayList<>();
        idIndexMap = new HashMap<>();
        loadStudents();
    }
    private void loadStudents() {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_NAME))) {
            students = (List<Student>) ois.readObject();
            for (int i = 0; i < students.size(); i++) {
                idIndexMap.put(students.get(i).getId(), i);
            }
        } catch (FileNotFoundException e) {
            // File not found, initialize empty list
            students = new ArrayList<>();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void saveStudents(){
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_NAME))) {
            oos.writeObject(students);
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void addStudent() {
        Scanner scanner = new Scanner(System.in);
        while(true) {
            System.out.print("请输入学号：");
            String id = scanner.nextLine();
            if(idIndexMap.containsKey(id)){
                System.out.println("学号重复，请重新输入。");
                continue;
            }
            System.out.print("请输入姓名：");
            String name = scanner.nextLine();
            System.out.print("请输入电话：");
            String phone = scanner.nextLine();

            Student student = new Student(id,name,phone);
            students.add(student);
            idIndexMap.put(id,students.size() - 1);
            saveStudents();
            System.out.println("学生信息添加成功！");
            break;
        }
    }

    private void retrieveStudent(){
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.print("请输入学号检索学生信息（输入QUIT退出）：");
            String input = scanner.nextLine();
            if (input.equalsIgnoreCase("QUIT")){
                break;
            }
            Integer index = idIndexMap.get(input);
            if (index != null) {
                System.out.println(students.get(index));
            }else{
                System.out.println("未找到该学生。");
            }
        }
    }
    private void updateStudent() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("请输入学号更新学生信息 (输入QUIT退出): ");
            String input = scanner.nextLine();
            if (input.equalsIgnoreCase("QUIT")) {
                break;
            }
            Integer index = idIndexMap.get(input);
            if (index != null) {
                Student student = students.get(index);
                System.out.print("请输入新姓名: ");
                String name = scanner.nextLine();
                System.out.print("请输入新电话: ");
                String phone = scanner.nextLine();

                student.setName(name);
                student.setPhone(phone);
                saveStudents();
                System.out.println("学生信息更新成功！");
            } else {
                System.out.println("未找到该学生。");
            }
        }
    }

    private void deleteStudent(){
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.print("请输入学号更新学生信息 (输入QUIT退出):");
            String input = scanner.nextLine();
            if (input.equalsIgnoreCase("QUIT")){
                break;
            }
            Integer index = idIndexMap.get(input);
            if (index != null){
                students.remove(index);
                idIndexMap.values().remove(Integer.valueOf(index));
                for(Map.Entry<String ,Integer> entry : idIndexMap.entrySet()){
                    if (entry.getValue() >index){
                        entry.setValue(entry.getValue() - 1);
                    }
                }
                saveStudents();
                System.out.println("学生信息删除成功！");
            }else{
                System.out.println("未找到该学生。");
            }
        }
    }

    public void showMenu(){
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("======= 学生信息管理系统 =======");
            System.out.println("1.添加学生信息");
            System.out.println("2.检索学生信息");
            System.out.println("3.更新学生信息");
            System.out.println("4.删除学生信息");
            System.out.println("5.退出程序");
            System.out.println("请输入操作编号（1-5）：");
            int choice = scanner.nextInt();
            scanner.nextLine();

            switch(choice){
                case 1:
                    addStudent();
                    break;
                case 2:
                    retrieveStudent();
                    break;
                case 3:
                    updateStudent();
                    break;
                case 4:
                    deleteStudent();
                    break;
                case 5:
                    saveStudents();
                    System.out.println("程序已退出。");
                    return;
                default:
                    System.out.println("无效的选择，请重新输入。");
            }
        }
    }

    public static void main(String[] args) {
        new StudentManagementSystem().showMenu();
    }
}
